import { requireLogin, checkLogin } from '../../utils/auth'
import { createAndPayOrder } from '../../utils/order'
import { 
  showToast, 
  showLoading, 
  hideLoading, 
  showConfirm,
  chooseAddress,
  chooseDeliveryType,
  DELIVERY_TYPE
} from '../../utils/tips'

const app = getApp()

Page({
  data: {
    cartList: [],
    selectedItems: [],
    selectedAll: false,
    totalAmount: 0
  },

  onShow() {
    console.log('onShow triggered')
    if (app.globalData.isLoggedIn) {
      // 只在必要时加载购物车列表
      if (this.data.cartList.length === 0) {
        console.log('Loading cart list because cart is empty')
        this.loadCartList()
      } else {
        console.log('Cart list already loaded, skipping reload')
      }
    }
  },

  // 加载购物车列表
  async loadCartList() {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('cart').where({
        userId: app.globalData.openid
      }).get()
      
      // 保存当前选中状态的映射
      const selectedMap = {}
      this.data.selectedItems.forEach(id => {
        selectedMap[id] = true
      })
      
      data.forEach(cart => {
        cart.products.forEach(product => {
          product.uniqueId = `${cart._id}-${product.id}`
          // 设置选中状态
          product.checked = selectedMap[product.uniqueId] || false
        })
      })
      
      this.setData({ 
        cartList: data
      }, () => {
        this.updateSelectedItems()
        this.checkSelectAll()
        this.calculateTotal()
      })
    } catch (error) {
      console.error('加载购物车失败：', error)
    }
  },

  // 选择商品
  onSelectItem(e) {
    const uniqueId = e.currentTarget.dataset.uniqueid
    const cartList = [...this.data.cartList]
    
    // 更新商品的选中状态
    cartList.forEach(cart => {
      cart.products.forEach(product => {
        if (product.uniqueId === uniqueId) {
          product.checked = !product.checked
        }
      })
    })
    
    this.setData({ 
      cartList,
      selectedAll: false
    }, () => {
      this.updateSelectedItems()
      this.checkSelectAll()
      this.calculateTotal()
    })
  },

  // 全选/取消全选
  onSelectAll() {
    const { cartList, selectedAll } = this.data
    const newCartList = [...cartList]
    let selectedItems = []
    
    // 更新所有商品的选中状态
    newCartList.forEach(cart => {
      cart.products.forEach(product => {
        // 根据全选状态设置每个商品的 checked 属性
        product.checked = !selectedAll
        if (!selectedAll) {
          selectedItems.push(product.uniqueId)
        }
      })
    })
    
    this.setData({
      selectedAll: !selectedAll,
      cartList: newCartList,
      selectedItems
    }, () => {
      this.calculateTotal()
    })
  },

  // 检查是否全选
  checkSelectAll() {
    const { cartList, selectedItems } = this.data;
    let total = 0;
    
    // 计算商品总数
    cartList.forEach(cart => {
      cart.products.forEach(() => {
        total++;
      });
    });
    
    // 添加日志
    console.log('checkSelectAll - selectedItems:', selectedItems);
    console.log('checkSelectAll - total:', total);
    
    // 更新全选状态
    this.setData({
      selectedAll: selectedItems.length === total && total > 0
    });
  },

  // 计算总金额
  calculateTotal() {
    const { cartList, selectedItems } = this.data;
    let total = 0;
    
    // 添加日志
    console.log('calculateTotal - selectedItems:', selectedItems);
    
    cartList.forEach(cart => {
      cart.products.forEach(product => {
        if (selectedItems.includes(product.uniqueId)) {
          total += product.price * product.quantity;
        }
      });
    });
    
    this.setData({
      totalAmount: total.toFixed(2)
    });
  },

  // 调整商品数量
  async adjustQuantity(e) {
    const { cartid, productid, type } = e.currentTarget.dataset
    const cartList = [...this.data.cartList]
    const cart = cartList.find(item => item._id === cartid)
    const product = cart.products.find(item => item.id === productid)
    
    if (type === 'minus' && product.quantity > 1) {
      product.quantity--
    } else if (type === 'plus') {
      product.quantity++
    } else {
      return
    }
    
    try {
      const db = wx.cloud.database()
      await db.collection('cart').doc(cartid).update({
        data: {
          products: cart.products,
          updateTime: db.serverDate()
        }
      })
      
      this.setData({ cartList })
      this.calculateTotal()
    } catch (error) {
      console.error('更新商品数量失败：', error)
    }
  },

  // 删除商品
  async deleteProduct(e) {
    const { cartid, productid } = e.currentTarget.dataset
    
    try {
      const { confirm } = await wx.showModal({
        title: '确认删除',
        content: '确定要删除这个商品吗？'
      })
      
      // 只有用户点击了确定才执行删除操作
      if (!confirm) {
        return; // 用户点击取消，直接返回
      }
      
      const cartList = [...this.data.cartList]
      const cartIndex = cartList.findIndex(item => item._id === cartid)
      const cart = cartList[cartIndex]
      const productIndex = cart.products.findIndex(item => item.id === productid)
      
      cart.products.splice(productIndex, 1)
      
      const db = wx.cloud.database()
      if (cart.products.length > 0) {
        await db.collection('cart').doc(cartid).update({
          data: {
            products: cart.products,
            updateTime: db.serverDate()
          }
        })
      } else {
        await db.collection('cart').doc(cartid).remove()
        cartList.splice(cartIndex, 1)
      }
      
      // 移除选中状态
      const selectedItems = this.data.selectedItems.filter(
        item => item !== `${cartid}-${productid}`
      )
      
      this.setData({ 
        cartList,
        selectedItems
      })
      this.checkSelectAll()
      this.calculateTotal()
      
      wx.showToast({
        title: '删除成功'
      })
    } catch (error) {
      console.error('删除商品失败：', error)
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      })
    }
  },

  // 结算
  async settlement() {
    if (!checkLogin()) return
    const { cartList, selectedItems } = this.data
    if (selectedItems.length === 0) {
      showToast('请选择商品')
      return
    }

    try {
      // 获取选中的商品
      const products = []
      cartList.forEach(cart => {
        cart.products.forEach(product => {
          if (selectedItems.includes(`${cart._id}-${product.id}`)) {
            products.push(product)
          }
        })
      })

      // 显示确认提示
      const confirmContent = products.map(product => 
        `${product.name}\n数量：${product.quantity}件`
      ).join('\n\n')

      const confirmResult = await showConfirm(
        '确认购买',
        `${confirmContent}\n\n总计：¥${this.data.totalAmount}`
      )

      if (!confirmResult.confirm) return

      // 选择配送方式
      const deliveryType = await chooseDeliveryType()
      
      let address = null
      if (deliveryType.value === DELIVERY_TYPE.DELIVERY.value) {
        // 需要配送时才选择地址
        // 选择收货地址前先检查权限
        const setting = await wx.getSetting()
        if (!setting.authSetting['scope.address']) {
          await wx.authorize({
            scope: 'scope.address'
          })
        }

        // 选择收货地址
        showLoading('正在选择地址...')
        address = await chooseAddress()
        hideLoading()
        
        if (!address) {
          throw new Error('请选择收货地址')
        }
      }

      // 创建并支付订单
      const orderData = {
        shopId: products[0].shopId,
        shopName: products[0].shopName || '',
        products,
        totalAmount: this.data.totalAmount,
        deliveryType: deliveryType.value,
        deliveryTypeDesc: deliveryType.desc
      }

      // 如果需要配送，添加地址信息
      if (address) {
        orderData.address = {
          name: address.name,
          phone: address.phone,
          province: address.province,
          city: address.city,
          district: address.district,
          detail: address.detail
        }
      }

      const { orderId } = await createAndPayOrder(orderData)

      // 从购物车移除商品
      await this.removeCheckedItems()

      // 跳转到订单详情页
      wx.redirectTo({
        url: `/pages/order/detail?id=${orderId}`,
        fail: (error) => {
          console.error('跳转失败：', error)
          showToast('跳转订单页面失败')
        }
      })

    } catch (error) {
      hideLoading()
      console.error('结算失败：', error)
      showToast(error.message || '结算失败，请重试')
    }
  },

  // 从购物车中移除已购买的商品
  async removeCheckedItems() {
    try {
      showLoading('正在处理...')
      
      const { cartList, selectedItems } = this.data
      const db = wx.cloud.database()
      
      // 遍历购物车列表
      for (const cart of cartList) {
        // 过滤出未选中的商品
        const remainingProducts = cart.products.filter(product => 
          !selectedItems.includes(`${cart._id}-${product.id}`)
        )
        
        if (remainingProducts.length === 0) {
          // 如果没有剩余商品，删除整个购物车记录
          await db.collection('cart').doc(cart._id).remove()
        } else {
          // 更新购物车中的商品
          await db.collection('cart').doc(cart._id).update({
            data: {
              products: remainingProducts,
              updateTime: db.serverDate()
            }
          })
        }
      }
      
      // 重新加载购物车列表
      this.loadCartList()
    } catch (error) {
      console.error('移除商品失败：', error)
      showToast('移除商品失败')
    } finally {
      hideLoading()
    }
  },

  // 更新选中项数组
  updateSelectedItems() {
    const selectedItems = []
    this.data.cartList.forEach(cart => {
      cart.products.forEach(product => {
        if (product.checked) {
          selectedItems.push(product.uniqueId)
        }
      })
    })
    this.setData({ selectedItems })
  }
}) 